from typing import Annotated, Optional

from fastapi import Query, Body
from pydantic import model_validator

from app.utils import types
from app.models.common import AppId, Pagination
from app.models import responses


class AppDeviceList(AppId, Pagination):
    """分页获取指定应用的设备列表"""
    used_card: str
    status: Optional[int]
    device_code: str

    @model_validator(mode='before')
    @classmethod
    def before(cls, data):
        data = types.safe_dict(data)
        data['used_card'] = data.get('used_card', '')
        data['status'] = types.safe_int(data.get('status', None), None)
        data['device_code'] = data.get('device_code', '')
        return data

    @model_validator(mode='after')
    def after(self):
        if len(self.used_card) > 64:
            raise responses.FailureResponseError(-102, msg='查询使用过卡密的长度不能超过 64 位')

        if self.status is not None and not (0 <= self.status <= 255):
            raise responses.FailureResponseError(-102, msg='设备的状态值应介于 0-255 之间')

        if len(self.device_code) > 128:
            raise responses.FailureResponseError(-102, msg='设备码长度不能超过 128 位')

        return self


AppDeviceListParams = Annotated[AppDeviceList, Query()]


class BatchAppDeviceIds(AppId):
    device_ids: list[int] = []

    @model_validator(mode='before')
    @classmethod
    def before(cls, data):
        data = types.safe_dict(data)
        device_ids = []
        for raw_device_id in list(data.get('device_ids', [])):
            device_id = types.safe_int(raw_device_id, None)
            if device_id is not None:
                device_ids.append(device_id)

        data['device_ids'] = device_ids
        return data

    @model_validator(mode='after')
    def after(self):
        if type(self.device_ids) is not list:
            raise responses.FailureResponseError(-102, msg='多个设备 ID 必须是列表类型')

        if len(self.device_ids) == 0:
            raise responses.FailureResponseError(-102, msg='请传入至少 1 个设备 ID')

        return self


BatchDeleteAppDevicesJSON = Annotated[BatchAppDeviceIds, Body()]


class DeviceCardsList(AppId):
    device_code: str

    @model_validator(mode='before')
    @classmethod
    def before(cls, data):
        data = types.safe_dict(data)
        data['device_code'] = data.get('device_code', '')
        return data

    @model_validator(mode='after')
    def after(self):
        if len(self.device_code) > 128:
            raise responses.FailureResponseError(-102, msg='设备码长度不能超过 128 位')

        return self


DeviceCardsListParams = Annotated[DeviceCardsList, Query()]
